CREATE TRIGGER TGNV_01 ON NHANVIEN
FOR INSERT, UPDATE
AS
BEGIN
	DECLARE @GIOITINH VARCHAR(30)
	SET @GIOITINH = (SELECT GIOITINH FROM inserted)
	IF(@GIOITINH = 'NAM' OR @GIOITINH = 'NU')
	BEGIN
		RETURN
	END
	ELSE
		BEGIN
			RAISERROR('GIOI TINH PHAI LA NAM HOAC NU',16,1)
			ROLLBACK TRAN
			RETURN
		END
		
END

CREATE TRIGGER TGNV_02 ON NHANVIEN
INSTEAD OF DELETE
AS
BEGIN
	DECLARE @MANV VARCHAR(15)
	SET @MANV = (SELECT MANV FROM deleted)
	DELETE FROM PhieuNhap WHERE @MANV = MaNV
	DELETE FROM HoaDon WHERE @MANV = MaNhanVien
	DELETE FROM NhanVien WHERE MaNV = @MANV
	RAISERROR('XOA THONG TIN THANH CONG',16,1)
END

CREATE TRIGGER TGNV_03 ON NHANVIEN
FOR INSERT,UPDATE
AS
BEGIN
	DECLARE @SODT VARCHAR(15)
	DECLARE @COUNT INT
	SET @SODT = (SELECT SoDienThoai FROM inserted)
	SET @COUNT = (SELECT COUNT(*) FROM NhanVien WHERE SoDienThoai = @SODT)
	IF(@COUNT > 1)
	BEGIN
		RAISERROR('SO DIEN THOAI BI TRUNG',16,1)
		ROLLBACK TRAN
		RETURN
	END
END

CREATE TRIGGER TGNV_04 ON NHANVIEN
FOR INSERT,UPDATE
AS
BEGIN
	DECLARE @SOCMND VARCHAR(15)
	DECLARE @COUNT INT
	SET @SOCMND = (SELECT SoCMND FROM inserted)
	SET @COUNT = (SELECT COUNT(*) FROM NhanVien WHERE SoCMND = @SOCMND)
	IF(@COUNT > 1)
	BEGIN
		RAISERROR('SO CMND BI TRUNG',16,1)
		ROLLBACK TRAN
		RETURN
	END
END


CREATE TRIGGER TGNV_05 ON NHANVIEN
FOR INSERT
AS
BEGIN
	DECLARE @USERNAME VARCHAR(50)
	DECLARE @PASS VARCHAR(50)
	SET @USERNAME = (SELECT MaNV FROM inserted)
	SET @PASS = (SELECT PASSWORD FROM inserted)
	BEGIN
		INSERT INTO DangNhap VALUES (@USERNAME,@PASS)
	END
END


CREATE TRIGGER TGNV_06 ON NHANVIEN
FOR UPDATE
AS
BEGIN
	DECLARE @PASS VARCHAR(50)
	DECLARE @MANV VARCHAR(30)
	SET @MANV = (SELECT MANV FROM inserted)
	SET @PASS = (SELECT PASSWORD FROM inserted)
	BEGIN
		UPDATE DangNhap SET PASSWORD = @PASS WHERE USERNAME = @MANV 
	END
END